package top.soulblack.purchasesale.controller.wechat;

import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.soulblack.purchasesale.controller.wechat.config.WechatEditConfig;
import top.soulblack.purchasesale.mapper.WechatGeneralAccessMapper;
import top.soulblack.purchasesale.mapper.WechatTableClassifyMapper;
import top.soulblack.purchasesale.mapper.WechatTableColumnMapper;
import top.soulblack.purchasesale.mapper.WechatTablePageMapper;
import top.soulblack.purchasesale.model.*;
import top.soulblack.purchasesale.service.WechatAccessService;
import top.soulblack.purchasesale.service.WechatEditService;
import top.soulblack.purchasesale.service.WechatNavService;
import top.soulblack.purchasesale.service.WechatPageComponentService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/***
 * @Author li
 * @Description //TODO
 * @Date 9:36 2019/8/6
 */
@Controller
@RequestMapping("/wechat")
public class WechatController extends BaseController {

    @Autowired
    private WechatNavService wechatNavService;
    @Autowired
    private WechatTablePageMapper wechatTablePageMapper;
    @Autowired
    private WechatPageComponentService wechatPageComponentService;
    @Autowired
    private WechatTableClassifyMapper wechatTableClassifyMapper;
    @Autowired
    private WechatTableColumnMapper wechatTableColumnMapper;
    @Autowired
    private WechatAccessService wechatAccessService;
    @Autowired
    private WechatEditService wechatEditService;
    @Autowired
    private WxMpService wxMpService;

    /***
     * @Author li
     * @Description 主页控制器
     * @Date 9:42 2019/8/6
     * @Param [request, model]
     * @return java.lang.String
     */
    @RequestMapping("/index")
    public String Index(HttpServletRequest request, Model model) {
        HttpSession httpSession = request.getSession();
        //TODO:完成登陆验证
        List<Role> roles = (List<Role>) httpSession.getAttribute("WebSecurityConfig.ROLES");
//        if (UINFO == null){
//            return "redirect:/login";
//        }
        try {
            WxJsapiSignature jsapiSignature = wxMpService.createJsapiSignature(request.getRequestURL().toString());
            model.addAttribute("jsapiSignature", jsapiSignature);
        } catch (WxErrorException e) {

        }
        List<WechatNav> wechatNavs = wechatNavService.getUserMainNav(roles);
        List<WechatNav> perLoadPage = wechatNavService.getPerloadList();
        model.addAttribute("wechatNavs", wechatNavs);
        model.addAttribute("perloadPages", perLoadPage);
        return "wechat/index/index";
    }

    @GetMapping("/pageloader")
    public String PageLoader(HttpServletRequest request, Model model) {
        HttpSession httpSession = request.getSession();
        Object UINFO = httpSession.getAttribute("WebSecurityConfig.UINFO");
        //TODO:完成登陆验证

        Integer pid = Integer.parseInt(request.getParameter("id"));
        /*获取内容，并分组*/
        List<WechatNav> childNavs = wechatNavService.getUserChildPageNav(pid);
        Map<Integer, List<WechatNav>> wechatPidMap = new LinkedHashMap<>();
        for (WechatNav wechatNav : childNavs) {
            List<WechatNav> tempList = wechatPidMap.get(wechatNav.getGroup());
            /*如果取不到数据,那么直接new一个空的ArrayList**/
            if (tempList == null) {
                tempList = new ArrayList<>();
                tempList.add(wechatNav);
                wechatPidMap.put(wechatNav.getGroup(), tempList);
            } else {
                /*之前已经存放过了,则直接追加数据到原来的List里**/
                tempList.add(wechatNav);
            }
        }
        /*获取父节点信息*/
        WechatNav parentNav = wechatNavService.getById(pid);
        model.addAttribute("childNavs", wechatPidMap);
        model.addAttribute("parentNav", parentNav);
        User fadeUser = new User();
        fadeUser.setAccount("这是假的用户");
        fadeUser.setPhone("这是假的电话");
        model.addAttribute("user", fadeUser);
        return "wechat/index/pageloader";
    }

    @GetMapping("/chatdetail")
    public String ChatDetail(HttpServletRequest request, Model model, HttpServletResponse response) {
        Map<String, String[]> para = request.getParameterMap();
        if (!para.containsKey("chatId")) {
            return error(model, "无效的访问参数");
        }
        Integer tableId = Integer.parseInt(para.get("chatId")[0]);
        WechatTablePage wechatTablePage = wechatTablePageMapper.selectByPrimaryKey(tableId);
        if (wechatTablePage.getPid() != 0) {
            return error(model, "非法的访问参数");
        }
        WechatTableClassify tableClassify = wechatTableClassifyMapper.selectByPrimaryKey(wechatTablePage.getImpactTable());
        List<WechatTablePage> components = wechatPageComponentService.getPageComponents(tableId, para);
        model.addAttribute("page", wechatTablePage);
        model.addAttribute("table", tableClassify);
        model.addAttribute("pageComponents", components);
        return "wechat/index/chatdetail";
    }

    @GetMapping("/edit")
    public String ChatEdit(HttpServletRequest request, Model model) {
        Map<String, String[]> para = request.getParameterMap();
        if (!para.containsKey("pageId")) {
            return error(model, "无效的访问参数");
        }
        WechatEditConfig wechatEditConfig = wechatEditService.getEditConfig(Integer.parseInt(para.get("pageId")[0]));
        Map<String, Object> data = new HashMap<>();
        int id = -1;
        //如果包含主键信息
        if (para.containsKey("id")) {
            id = Integer.parseInt(para.get("id")[0]);
            WechatTableColumn indexCol = wechatTableColumnMapper.selectByPrimaryKey(wechatEditConfig.page.getColIndex());
            List<String> columns = new ArrayList<>();
            for (WechatTableColumn column : wechatEditConfig.columns.get(indexCol.getPid())) {
                columns.add(column.getName());
            }
            //获取索引下的数据
            data = wechatAccessService.selectByPrimaryKey(
                    wechatEditConfig.tables.get(indexCol.getPid()),
                    Integer.parseInt(para.get("id")[0]));

            data = data==null?new HashMap<>():data;
        }
        model.addAttribute("id",id);
        model.addAttribute("queryString",request.getQueryString());
        model.addAttribute("parameterMap",para);
        model.addAttribute("data",data);
        model.addAttribute("page", wechatEditConfig.page);
        model.addAttribute("tables", wechatEditConfig.tables);
        model.addAttribute("tableConfigs", wechatEditConfig.tableConfig);
        model.addAttribute("columns", wechatEditConfig.columns);
        model.addAttribute("paddingData", wechatEditConfig.paddingData);
        model.addAttribute("linkTables", wechatEditConfig.linkTables);
         return "wechat/index/edit";
    }

    @ResponseBody
    @PostMapping("/edit")
    public String ChatSave(HttpServletRequest request, Model model) {
        Map<String, String[]> ParameterMap = request.getParameterMap();
        if (!ParameterMap.containsKey("pageId")) {
            return Result.error("参数错误");
        }
        wechatEditService.saveEdit(Integer.parseInt(ParameterMap.get("pageId")[0]),ParameterMap);
        return Result.success("保存成功");
    }

    @GetMapping("/login")
    public String Login(HttpServletRequest request, Model model) {
        return "wechat/common/login";
    }

//    private Boolean GetAuth() {
//        return true;
//    }
}
